package easier.app.x.view;

import android.graphics.Rect;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 为GridLayoutManager设置等分间隔
 */
public class GridLayoutSpaceSpreadDecoration extends RecyclerView.ItemDecoration {

    private final int mSpanCount;//横条目数量
    private final float mCellOffset;//基础偏移量

    public GridLayoutSpaceSpreadDecoration( int spanCount, float space ) {

        this.mSpanCount = spanCount;

        //行间距
        float totalSpace = (spanCount + 1) * space;
        float cellWidthOffset = totalSpace / spanCount;
        mCellOffset = cellWidthOffset / (spanCount + 1);
    }

    @Override
    public void getItemOffsets( @NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent,
        @NonNull RecyclerView.State state ) {

        if ( mSpanCount == 1 ) {
            return;
        }

        int position = parent.getChildAdapterPosition( view );
        int right = position % (mSpanCount) + 1;
        int left = mSpanCount + 1 - right;

        outRect.left = (int) (left * mCellOffset);
        outRect.right = (int) (right * mCellOffset);
    }
}